package com.ys.erp.framework.validator;

import com.ys.erp.framework.annotation.valid.EnumsValid;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @author lwj
 * @date 2023/9/21
 */
public class EnumValidator implements ConstraintValidator<EnumsValid, String> {

    Map<?, ?> enumMap;

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.isEmpty(value)) {
            return true;
        }
        return enumMap.containsKey(value);
    }

    @Override
    public void initialize(EnumsValid en) {
        Class<?> targetClass = en.enumClass();
        try {
            Field enumMapField = targetClass.getField("ENUM_MAP");
            enumMap = (Map<?, ?>) enumMapField.get(null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
